package org.nanyuan.forum.service.impl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.nanyuan.forum.common.AppResult;
import org.nanyuan.forum.common.ResultCode;
import org.nanyuan.forum.dao.ArticleMapper;
import org.nanyuan.forum.exception.ApplicationException;
import org.nanyuan.forum.model.Article;
import org.nanyuan.forum.model.Board;
import org.nanyuan.forum.model.User;
import org.nanyuan.forum.service.IArticleService;
import org.nanyuan.forum.service.IBoardService;
import org.nanyuan.forum.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Resource
    private ArticleMapper articleMapper;
    //用户操作
    @Resource
    private IUserService userService;
    //板块操作
    @Resource
    private IBoardService boardService;

    @Transactional
    @Override
    public void create(Article article) {
        //非空校验
        if (article == null || article.getUserId() == null || article.getBoardId() == null
        || !StringUtils.hasLength(article.getTitle())
        || !StringUtils.hasLength(article.getContent()) ) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0);   //访问量
        article.setReplyCount(0);   //回复量
        article.setLikeCount(0);    //点赞量
        article.setDeleteFlag((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        //更新用户的发帖数
        User user = userService.selectById(article.getUserId());  //获取用户信息
        //用户不存在
        if (user == null) {
            //打印日志
            log.warn("{},发帖失败,user id:{}", ResultCode.FAILED_CREATE.toString(), article.getUserId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户发帖数
        userService.addOneArticleCountById(user.getId());

        //获取板块信息
        Board board = boardService.selectById(article.getBoardId());
        //是否存在对应的板块
        if (board == null) {
            //打印日志
            log.warn("{},发帖失败,board id:{}", ResultCode.FAILED_CREATE.toString(), article.getBoardId());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块的帖子数
        boardService.addOneArticleCountById(board.getId());

        //打印日志
        log.info("{}user id = {}成功发布贴子article id = {}", ResultCode.SUCCESS.toString(), article.getUserId(), article.getId());
    }

    @Override
    public List<Article> selectAll() {
        //调用dao
        List<Article> articles = articleMapper.selectAll();
        //返回结果集
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if (boardId == null || boardId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null) {
            //打印日志
            log.warn("{}boardId:{}", ResultCode.FAILED_BOARD_NOT_EXISTS.toString(), boardId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        //调用dao
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        //返回结果
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Article article = articleMapper.selectDetailById(id);
        //判断结果是否有效
        if (article == null) {
            //打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //更新访问量
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount() + 1);
        //存入数据库
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //将当前帖子的访问数据更新
        article.setVisitCount(article.getVisitCount() + 1);
        //访问帖子详情
        return article;
    }

    @Override
    public Article selectById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Article article = articleMapper.selectByPrimaryKey(id);


        return article;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        //非空校验
        if (userId == null || userId <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户是否存在
        User user = userService.selectById(userId);
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString(),"userId:{}",userId);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用dao
        List<Article> articles = articleMapper.selectByUserId(userId);
        //返回结果
        return articles;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if (id == null || id <= 0
        || !StringUtils.hasLength(title) || !StringUtils.hasLength(content)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(id);   //id
        updateArticle.setTitle(title);  //标题
        updateArticle.setContent(content);   //正文
        updateArticle.setCreateTime(new Date());  //更新时间
        //调用DAO
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //对结果进行校验
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    /*
    * 点赞操作
    * */
    @Override
    public void thumbsUpById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询帖子
        Article article = articleMapper.selectByPrimaryKey(id);
        //帖子不存在
        if (article == null || article.getDeleteFlag() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //构造要更新的对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount() + 1);
        updateArticle.setCreateTime(new Date());

        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        //对结果进行校验
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Transactional
    @Override
    public void deleteById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteFlag() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setBoardId(article.getBoardId());
        updateArticle.setUserId(article.getUserId());
        updateArticle.setDeleteFlag((byte) 1);
        //调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新相关的帖子数
        boardService.subOneArticleCountById(updateArticle.getBoardId());
        userService.subOneArticleCountById(updateArticle.getUserId());
        //打印日志
        log.info("删除成功，articleId:{},userId:{}",article.getId(),article.getUserId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //对帖子状态进行校验
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteFlag() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount() + 1);

        //执行更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
